package com.whl.pet.service.impl;

import com.whl.basic.exception.BusinessException;
import com.whl.basic.service.IBaiduAiAuditService;
import com.whl.basic.util.*;
import com.whl.order.domain.OrderPetAcquisition;
import com.whl.order.mapper.OrderPetAcquisitionMapper;
import com.whl.org.domain.Employee;
import com.whl.org.domain.Shop;
import com.whl.org.mapper.EmployeeMapper;
import com.whl.org.mapper.ShopMapper;
import com.whl.pet.domain.Pet;
import com.whl.pet.domain.SearchMasterMsg;
import com.whl.pet.domain.SearchMasterMsgAuditLog;
import com.whl.pet.dto.MsgDto;
import com.whl.pet.mapper.PetMapper;
import com.whl.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.whl.pet.mapper.SearchMasterMsgMapper;
import com.whl.pet.query.SearchMasterMsgQuery;
import com.whl.pet.service.ISearchMasterMsgService;
import com.whl.basic.service.impl.BaseServiceImpl;
import com.whl.user.domain.Logininfo;
import com.whl.user.domain.User;
import com.whl.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    /**
     * 发布寻主消息
     * @param searchMasterMsg
     * @param request
     */
    @Override
    public void publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        // 获取发布寻主消息的用户
        Logininfo logininfo = LoginContext.getLoginUser(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        // 1.添加寻主消息
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);
        // 2.智能审核
        Boolean textAuditBoo = baiduAiAuditService.textAudit(searchMasterMsg.getName() + ","+ searchMasterMsg.getTitle() + "," + searchMasterMsg.getAddress());
        Boolean imageAuditBoo = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        if(textAuditBoo && imageAuditBoo){ // 审核通过
            // 2.1审核通过：修改寻主消息状态为1【审核通过待处理】 + 将当前寻主消息分配给最近的门店+ 发短息给他 + 添加审核日志
            // 设置状态和日志
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核成功");

            // 绑定店铺
            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            // 50公里以内
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.findAll());
            if(nearestShop != null){
                searchMasterMsg.setShopId(nearestShop.getId());
                System.out.println("你有新的订单，请注意查收！！" + searchMasterMsg.getTitle());
            }

            searchMasterMsgMapper.update(searchMasterMsg);

            // 添加日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            // audit_id - 审核人id - 自动审核 - 没有添加审核人
            log.setState(1);
            log.setNote("审核通过，恭喜你!!!");
            searchMasterMsgAuditLogMapper.save(log);

        }else { // 审核失败
            // 修改状态和日志
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核失败，内容非法!!!");
            searchMasterMsgMapper.update(searchMasterMsg);

            // 2.2审核失败：修改寻主消息状态为0 + 添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            // audit_id - 审核人id - 自动审核 - 没有添加审核人
            log.setState(0); // 驳回
            log.setNote("审核失败，内容非法!!!");
            searchMasterMsgAuditLogMapper.save(log);
            throw new BusinessException("审核失败，内容非法!!!");
        }


    }

    /**
     *  用户的寻主消息
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 获取发布寻主消息的用户
        Logininfo logininfo = LoginContext.getLoginUser(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        // 设置用户id
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    /**
     * 审核通过待处理的寻主消息
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> tohandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 获取发布寻主消息的员工
        Logininfo logininfo = LoginContext.getLoginUser(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        // 如果当前管理员是店铺管理员：要设置shopId
        // 如果当前管理员是平台管理员：不设置shopId
        if(employee.getShop_id() != null){ // 说明他是店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    /**
     * 拒单
     * @param msgId
     */
    @Override
    public void reject(Long msgId) {
        searchMasterMsgMapper.reject(msgId);
    }

    /**
     * 接单
     * @param msgDto
     */
    @Override
    public void accept(MsgDto msgDto) {
        Long empId = msgDto.getHandler();
        Employee employee = employeeMapper.findOne(empId);
        Long msgId = msgDto.getMsgId();
        String note = msgDto.getNote();

        // 1.校验：当前寻主消息是否已经被处理
        OrderPetAcquisition orderTmp = orderPetAcquisitionMapper.findByMsgId(msgId);
        if(orderTmp != null){
            throw new BusinessException("订单已处理，请耐心等待!!!");
        }

        // 2.创建宠物对象
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findOne(msgId);
        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        petMapper.save(pet);
        // 3.创建收购订单
        OrderPetAcquisition order = bulidOrder(searchMasterMsg, empId, pet);
        orderPetAcquisitionMapper.save(order);
        // 4.发短信通知
        System.out.println("你有新的订单，请尽快处理" + order.getDigest());
        System.out.println(employee.getEmail() + "-->邮件通知：你有新的" + order.getOrderSn() + "订单要处理");
    }

    // 创建订单的方法
    private OrderPetAcquisition bulidOrder(SearchMasterMsg searchMasterMsg, Long empId, Pet pet) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        // 调用工具类生成订单号orderSn
        String orderSn = CodeGenerateUtils.generateOrderSn(pet.getId());
        order.setOrderSn(orderSn);
        order.setState(0);
        order.setDigest(searchMasterMsg.getTitle());

        // 两天后的此刻是订单收购的最终时间
        Long timeTmp = System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000;
        order.setLastcomfirmtime(new Date(timeTmp));

        order.setPrice(searchMasterMsg.getPrice());
        order.setPetId(pet.getId());
        order.setUserId(searchMasterMsg.getUserId());
        order.setShopId(searchMasterMsg.getShopId());
        order.setAddress(searchMasterMsg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(searchMasterMsg.getId());
        return order;
    }

    // 将寻主消息对象searchMaster转成宠物对象pet
    private Pet searchMasterMsg2Pet(SearchMasterMsg searchMasterMsg) {
        Pet pet = new Pet();
        pet.setName(searchMasterMsg.getName());
        // 用户发布时需要的价格 收购回来就是成本价
        pet.setCostprice(searchMasterMsg.getPrice());
        pet.setTypeId(searchMasterMsg.getPetType());
        // 获取处理人的店铺id
        pet.setShopId(searchMasterMsg.getShopId());
        pet.setUserId(searchMasterMsg.getUserId());
        pet.setResources(searchMasterMsg.getResources());
        pet.setSearchMasterMsgId(searchMasterMsg.getId());
        return pet;
    }
}
